from typing import Optional

import httpx
from app.config import settings
import logging

logger = logging.getLogger(__name__)

class DeepSeekClient:
    def __init__(self):
        self.api_key = settings.DEEPSEEK_API_KEY
        self.client = httpx.AsyncClient(
            timeout=settings.API_TIMEOUT,
            limits=httpx.Limits(max_connections=settings.MAX_CONNECTIONS)
        )

    async def send_message(self, message: str):
        logger.info(settings)

        
        # 如果提供了图片，添加到消息中

        # 检查 API key 是否为空
        if not self.api_key:
            raise Exception("API key 未设置，请在 .env 文件中设置 DEEPSEEK_API_KEY")
        
        logger.info("准备发送请求到 DeepSeek API")
        headers = {
            "Authorization": f"Bearer {self.api_key.strip()}", # 确保删除可能的空格
            "Content-Type": "application/json"
        }
        
        payload = {
            "model": "deepseek-ai/DeepSeek-V3",
            "messages": [
                {
                    "role": "user",
                    "content": message
                }
            ],
            "stream": False,
            "max_tokens": 2048,
            "stop": ["null"],
            "temperature": 0.7,
            "top_p": 0.7,
            "top_k": 50,
            "frequency_penalty": 0.5,
            "n": 1,
            "response_format": {
                "type": "text"
            },
            "tools": None
        }
        
        try:
            response = await self.client.post(
                "https://api.siliconflow.cn/v1/chat/completions",
                json=payload,
                headers=headers
            )
            response.raise_for_status()
            logger.info(response.json())
            return response.json()
        except Exception as e:
            logger.error(f"API 调用失败: {str(e)}", exc_info=True)
            raise Exception(f"DeepSeek API error: {str(e)}")